package cn.turboinfo.fuyang.api.gateway.admin.controller.staff;


import cn.turboinfo.fuyang.api.domain.admin.usecase.staff.HousekeepingStaffSearchUseCase;
import cn.turboinfo.fuyang.api.entity.common.enumeration.user.UserType;
import cn.turboinfo.fuyang.api.entity.common.pojo.staff.HousekeepingStaff;
import cn.turboinfo.fuyang.api.entity.common.pojo.staff.QHousekeepingStaff;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.UserTypeRel;
import cn.turboinfo.fuyang.api.gateway.admin.fo.staff.HousekeepingStaffSearchFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.ResponseBodyWrapper;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitDataFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.SortFO;
import cn.turboinfo.fuyang.api.provider.admin.component.session.AdminSessionHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.request.QSort;
import net.sunshow.toolkit.core.qbean.helper.component.request.QBeanSearchHelper;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

/**
 * 家政公司家政员管理
 */
@Slf4j
@RequiredArgsConstructor
@Controller
@ResponseBodyWrapper
@RequestMapping("/admin/staff")
public class HousekeepingStaffController {

    private final HousekeepingStaffSearchUseCase housekeepingStaffSearchUseCase;
    private final AdminSessionHelper sessionHelper;

    @RequiresPermissions(value = {"staff:admin:list", "staff:list"}, logical = Logical.OR)
    @RequestMapping("/list")
    public  LimitDataFO<HousekeepingStaff> list(@Valid HousekeepingStaffSearchFO search, LimitFO page, SortFO sort) {
        Long companyId = sessionHelper.getSession().getUserTypeRelList().stream()
                .filter(userTypeRel -> userTypeRel.getUserType() == UserType.Company)
                .map(UserTypeRel::getObjectId).findFirst().orElse(null);
        if(companyId != null) {
            search.setCompanyId(companyId);
        }
        QRequest request = QBeanSearchHelper.convertQRequest(search);

        if (sort.getSortFields() == null) {
            sort.setSortFields(new String[]{QHousekeepingStaff.id + "|" + QSort.Order.DESC.name()});
        }
        HousekeepingStaffSearchUseCase.OutputData outputData = housekeepingStaffSearchUseCase.execute(HousekeepingStaffSearchUseCase.InputData
                .builder()
                .request(request)
                .requestPage(page.toQPage(sort.toQSortList()))
                .build());
        return LimitDataFO.fromQResponse(outputData.getQResponse());
    }

}
